package com.fin.zw.aiqas.util;

import com.fin.zw.aiqas.entity.Department;
import com.fin.zw.aiqas.model.component.TreeJson;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

public class TreeUtil {

    public static List<TreeJson> listToTree(List<Department> list) {
        List<TreeJson> treeJsons = new ArrayList<>();
        List<TreeJson> results = new ArrayList<>();
        for (Department department : list) {
            TreeJson treeJson = new TreeJson();
            BeanUtils.copyProperties(department, treeJson);
            if (Objects.nonNull(department.getParent())) {
                treeJson.setParentId(department.getParent().getId());
            }
            if (treeJson.getParentId() == null) {
                results.add(treeJson);
            } else {
                treeJsons.add(treeJson);
            }
        }
        Map<Long, List<TreeJson>> map = treeJsons.stream().collect(Collectors.groupingBy(TreeJson::getParentId));
        if (results != null && !results.isEmpty()) {
            for (TreeJson treeJson : results) {
                forEach(map, treeJson);
            }
        } else {
            TreeJson tree = getRoot(treeJsons, map);
            if (tree != null) {
                forEach(map, tree);
                results.add(tree);
            } else {
                results.addAll(treeJsons);
            }
        }
        return results;
    }

    public static TreeJson getRoot(List<TreeJson> list, Map<Long, List<TreeJson>> map) {
        for (TreeJson tree : list) {
            if (map.containsKey(tree.getId())) {
                return tree;
            }
        }
        return null;
    }


    public static void forEach(Map<Long, List<TreeJson>> collect, TreeJson treeMenuNode) {
        List<TreeJson> treeMenuNodes = collect.get(treeMenuNode.getId());
        if (collect.get(treeMenuNode.getId()) != null) {
            //排序
            treeMenuNodes.sort((u1, u2) -> u1.getId().compareTo(u2.getId()));
            treeMenuNodes.stream().sorted(Comparator.comparing(TreeJson::getId)).collect(Collectors.toList());
            treeMenuNode.setChildren(treeMenuNodes);
            treeMenuNode.getChildren().forEach(t -> {
                forEach(collect, t);
            });
        }
    }
}
